﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace WPFConsole
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    /// 

    public partial class PConsole : Window
    {
        byte[] Buffer { get; set; }

        Socket sck;

        delegate void CommandAction();
        delegate void ProtocolAction(List<string> toks);
        delegate void CmdArgsActions(string[] args);

        Dictionary<string, CommandAction> Commands = new Dictionary<string, CommandAction>();
        Dictionary<string, ProtocolAction> Numerics = new Dictionary<string, ProtocolAction>();
        Dictionary<string, CmdArgsActions> CmdArgs = new Dictionary<string, CmdArgsActions>();

        //WMPLib.WindowsMediaPlayer bgmusic = new WMPLib.WindowsMediaPlayer();

        bool Connected;

        bool NeedToStopParsingArgs = false;

        string WorldConsoleBackup = "";

        Thread Listener;

        public PConsole()
        {
            InitializeComponent();
            Connected = false;

            //Add the client side commands
            Commands.Add("connect", new CommandAction(ConnectCommand));
            Commands.Add("help", new CommandAction(HelpCommand));
            Commands.Add("disconnect", new CommandAction(DisconnectCommand));
            Commands.Add("ping", new CommandAction(PingCommand));
            Commands.Add("clear", new CommandAction(ClearCommand));

            //Add the server protocols
            Numerics.Add("0", new ProtocolAction(WorldProtocol));
            Numerics.Add("1", new ProtocolAction(ChatProtocol));
            Numerics.Add("2", new ProtocolAction(InventoryProtocol));
            Numerics.Add("3", new ProtocolAction(SoundProtocol));

            //Add command line arguments
            CmdArgs.Add("-connect", new CmdArgsActions(ConnectCommand));
            CmdArgs.Add("-login", new CmdArgsActions(LoginCommand));

        }

        private void rTitle_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        private void ClearInput()
        {
            if (tbInput.Dispatcher.Thread == Thread.CurrentThread)
            {
                tbInput.Text = "";
            }
            else
            {
                tbInput.Dispatcher.Invoke(new VoidMethod(ClearInput));
            }
            
        }

        delegate void VoidStringMethod(string text);
        delegate void VoidStringStringMethod(string user, string text);
        delegate void VoidMethod();

        public void WriteLine(string text)
        {
            if (tbConsole.Dispatcher.Thread == Thread.CurrentThread)
            {
                tbConsole.AppendText(text + Environment.NewLine);
                
                tbConsole.ScrollToEnd();
            }
            else
            {
                tbConsole.Dispatcher.Invoke(new VoidStringMethod(WriteLine), text);
            }
        }

        public void WriteLine(string user, string text)
        {
            if (tbChat.Dispatcher.Thread == Thread.CurrentThread)
            {
                tbChat.Text += '>' + user + ": " + text + Environment.NewLine;
                tbChat.ScrollToEnd();
            }
            else
            {
                tbChat.Dispatcher.Invoke(new VoidStringStringMethod(WriteLine), user, text);
            }
        }

        public string CurrentWorldText
        {
            get
            {
                return new TextRange(tbConsole.Document.ContentStart, tbConsole.Document.ContentEnd).Text;
            }
        }

        void SendToServer(string msg)
        {
            msg = msg.Trim();
            if (Connected && !string.IsNullOrWhiteSpace(msg))
            {
                byte[] data = Encoding.ASCII.GetBytes(msg);
                Array.Resize<byte>(ref data, sck.SendBufferSize);
                sck.Send(data);
            }
        }

        public void PreMadeInput(string text)
        {
            List<string> tokens = text.Split(' ').ToList<string>();
            tbInput.IsEnabled = false;
            tbInput.Text = text;
            if (tbChat.Dispatcher.Thread == Thread.CurrentThread)
            {
                if (Commands.ContainsKey(tokens[0].ToLower()))
                {
                    Commands[tokens[0].ToLower()]();
                }
                else if (Connected)
                {
                    SendToServer(text);
                    this.ClearInput();
                }
                else
                {
                    this.WriteLine(text);
                    this.ClearInput();
                }
            }
            else
            {
                tbChat.Dispatcher.Invoke(new VoidStringMethod(PreMadeInput), text);
            }
            tbInput.IsEnabled = true;
        }

        void Listen()
        {
            try
            {
                while (true)
                {

                    if (!sck.Connected) { throw new SocketException(10054); }

                    Buffer = new byte[sck.SendBufferSize];

                    int bytesRead = sck.Receive(Buffer,sck.SendBufferSize, SocketFlags.None);

                    if (bytesRead == 0)
                    {
                        Connected = false;
                        this.WriteLine("Server disconnected. Closing socket...");
                        sck.Close();
                        this.WriteLine("Socket closed. Successfully disconnected from server.");
                    }


                    /** Format buffer to take care of whitespace or extra crap*/
                    List<byte> formatted = new List<byte>(bytesRead);
                    for (int i = 0; i < bytesRead; i++)
                    {
                        if (Buffer[i] != default(byte))
                        {
                            formatted.Add(Buffer[i]);
                        }
                    }

                    string strData = Encoding.ASCII.GetString(formatted.ToArray()).Trim();
                    if (string.IsNullOrWhiteSpace(strData)) continue;
                    List<string> toks = strData.Split(' ').ToList<string>();
                    string protocol = toks[0];

                    if (Numerics.ContainsKey(protocol))
                    {
                        if (protocol != "2" && this.WorldConsoleBackup != "")
                        {
                            this.ClearCommand();
                            this.WriteLine(this.WorldConsoleBackup);
                            this.WorldConsoleBackup = "";
                        }
                        Numerics[protocol](toks);
                    }
                    else
                    {
                        this.WriteLine("Server sent erroneous protocol. Message was '"+strData+"'");
                    }
                }
            }
            catch (SocketException error)
            {
                this.WriteLine("Error: " + error.Message);
            }
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            string input = tbInput.Text;
            List<string> tokens = input.Split(' ').ToList<string>();
            if (e.Key == Key.Enter)
            {
                if (Commands.ContainsKey(tokens[0].ToLower()))
                {
                    Commands[tokens[0].ToLower()]();
                }
                else if (Connected)
                {
                    SendToServer(input);
                    this.ClearInput();
                }
                else
                {
                    this.WriteLine(input);
                    this.ClearInput();
                }
            }
        }

        private void eClose_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (Connected) sck.Close();
            this.Close();
        }

        private void eMinimize_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        private void MainWin_Loaded(object sender, RoutedEventArgs e)
        {
            string[] args = Environment.GetCommandLineArgs();
            foreach (string arg in args)
            {
                if (CmdArgs.ContainsKey(arg) && !NeedToStopParsingArgs)
                {
                    CmdArgs[arg](args);
                }
            }
        }
    }
}
